﻿using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using SmartMotion.Core.Properties;
using Sunny.UI;

// ReSharper disable once CheckNamespace
namespace SmartMotion.Core
{
    public class ToolMgr
    {
        #region 属性单例模式

        private static readonly Lazy<ToolMgr> Instance = new Lazy<ToolMgr>(() => new ToolMgr());

        private ToolMgr()
        {
            Tools = new List<ActionItem>();
            Images = new ConcurrentDictionary<string, Bitmap>();
            Path = Environment.CurrentDirectory + "\\Tools\\";
            if (!Directory.Exists(Path))
            {
                Directory.CreateDirectory(Path);
            }
        }
        public static ToolMgr Ins { get; } = Instance.Value;

        #endregion
            
        public string Path { get; set; }
        /// <summary>
        /// 序列化反序列化的工具集合，全部是半成品工具，没有配置参数
        /// </summary>
        public List<ActionItem> Tools;

        public ConcurrentDictionary<string, Bitmap> Images;


        public void SaveTools(ActionItem tool)
        {
            Json.SaveExt<ActionItem>(Path+ tool.ItemName + ".tool", tool);
        }

        public void LoadTools()
        {
            Tools.Clear();
            var files = Directory.GetFiles(Path, "*.tool");
            foreach (var file in files)
            {
                try
                {
                    var tool = Json.LoadExt<ActionItem>(file);
                    if (tool!=null)
                    {
                        Tools.Add(tool);
                        string iconPath = Path+ tool.Icon;
                        Image img;  //图片加密读取不上来
                        //if (File.Exists(iconPath))
                        //{
                        //    img=Image.FromFile(iconPath);
                        //}
                        //else
                        {
                            img = Resources.默认工具;
                            tool.Icon = Resources.默认工具.ToString();
                        }
                        img = ResizeImageHelper.ResizeImage(img, new Size(24, 24));
                        Images.TryAdd(tool.Icon, (Bitmap) img);
                    }
                }
                catch (Exception e)
                {
                    UIMessageBox.ShowError($"发现一个异常工具,工具名为{file}");
                }
            }
        }   

    }
}
